<template>
  <el-cascader
    style="width: 100%"
    ref="cascader"
    :props="casProps"
    filterable
    :options="dataList"
    clearable
    @change="handleChange"
  >
  </el-cascader>
</template>

<script>
import { getChildrenById } from '@/api/dispatch/shipRegistrationManagement/shipRegister'

export default {
  name: 'CascaderPlugin',
  data() {
    return {
      casProps: {
        value: 'id',
        label: 'sjmc',
        checkStrictly: true,
        lazy: true, // 此处必须为true
        lazyLoad: (node, resolve) => {
          if (node.data && node.data.id)
            this.getChildProject(node.data, resolve)
        }
      }
    }
  },

  props: {
    dataList: {
      type: Array,
      default: () => []
    },
    labelCode: {
      type: String,
      default: ''
    }
  },

  methods: {
    clearCascader() {
      let obj = {}
      obj.stopPropagation = () => {}
      try {
        this.$refs['cascader'].clearValue(obj)
      } catch (err) {
        this.$refs['cascader'].handleClear(obj)
      }
    },
    handleChange(value) {
      if (value.length > 0) {
        // 获取当前选中节点
        let checkNode = this.$refs['cascader'].getCheckedNodes()
        // 将当前选中节点数据和当前路径数组返回给父组件
        this.$emit(
          'getCascaderData',
          checkNode[0].data,
          checkNode[0].pathNodes,
          this.labelCode
        )
      } else {
        this.$emit('getCascaderData', {}, [], this.labelCode)
      }
    },
    // 获取子层数据
    getChildProject(data, resolve) {
      let params = {
        id: data.id
      }
      let childItems = []
      if (!data.children) {
        getChildrenById(params)
          .then(res => {
            childItems = res.data
            // 获取数据后调用resolve将子项数据渲染至视图
            resolve(childItems)
          })
          .catch(error => {
            // 此处调用resolve 防止接口数据异常时级联选择器一直处于加载状态
            resolve(childItems)
          })
      } else {
        resolve([])
      }
    }
  }
}
</script>
